import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import 'package:material_rfid_plugin/material_rfid_plugin.dart';
import '../utils/utils.dart';

class RfidScanPage extends StatefulWidget  {
  final Map arguments;

  RfidScanPage({Key key, this.arguments}) : super(key: key);

  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<RfidScanPage> {
  List<String> rfidList = [];

  @override
  void initState() {
    super.initState();
    openDevice();
  }

  @override
  void dispose() {
    super.dispose();
    stopInventory();
    closeDevice();
  }

  // 打开设备
  openDevice() async {
    print('开始初始化');
    bool isInit = await MaterialRfidPlugin.init;
    String openStatus = isInit ? '设备开启成功' : '设备开启失败';
    
    print(openStatus);

    if(isInit) {
      // startInventoryTag();
    }else {
      Utils.showText(text: openStatus);
    }
  }

  // 关闭设备
  closeDevice() async {
    bool isFree = await MaterialRfidPlugin.free;

    if(isFree) {
      print('关闭设备成功');
    }else {
      print('关闭设备失败');
    }
  }

  // 启动识别Tag循环
  startInventoryTag() async {
    bool isStart = await MaterialRfidPlugin.startInventoryTag(flagAnti: 0, initQ: 1);

    if(isStart) {
      print('启动识别Tag循环成功');
      readTagFromBuffer();
    }else {
      print('启动tag循环失败');
    }
  }

  // 从缓冲区读取数据
  readTagFromBuffer() async {
    List<String> data = await MaterialRfidPlugin.readTagFromBuffer;
    String uii = data[1];
    String epc = await MaterialRfidPlugin.convertUiiToEPC(uii: uii);

    if(epc != null) {
      addStringData(epc);
      stopInventory();
    }
  }

  // 停止循环识别
  stopInventory() async {
    bool data = await MaterialRfidPlugin.stopInventory;
    
    print('【停止循环识别】');
    print(data);
  }

  // 过滤重复数据
  void addStringData(String value){
    bool isContains = rfidList.contains(value);

    if(!isContains){
      rfidList.add(value);
    }

    setState(() {
      rfidList = rfidList;
    });

    print("数组长度${rfidList.length}");
    print(rfidList);
  }

  _buildTableRow() {
    List<TableRow> list = [];

    list.add(
      TableRow(
        //第一行样式 添加背景色
        decoration: BoxDecoration(
          color: Utils.hexToColor('#EBEAEA')
        ),
        children: [
          SizedBox(
            height: 40.0,
            child: Center(
              child: Text('序号',style: TextStyle(
                fontWeight: FontWeight.bold)
              ),
            )
          ),
          GestureDetector(
            onTap: () {},
            child: Center(
              child: Text('RFID标签号' + '(${rfidList.length})', style: TextStyle(
                fontWeight: FontWeight.bold
              )),
            )
          )
        ]
      ),
    );

    for(var i=0;i < rfidList.length; i++) {
      var rfid = rfidList[i];
      list.add(
        TableRow(
          children: [
            SizedBox(
              height: 40.0,
              child: Center(
                child: Text((i+1).toString()),
              )
            ),
            Center(
              child: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(context, "/rfid_detail", arguments: {'rfid': rfid});
                },
                child: Center(
                  child: Text(rfid.toString()),
                )
              )
            )
          ]
        )
      );
    }

    return list;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
      appBar: TopBar(
        title: '扫描结果',
      ),
      body: Container(
        color: Utils.hexToColor('#F5F6FA'),
        child: Stack(
          children: <Widget>[
            RawKeyboardListener(
              focusNode: FocusNode(),// 焦点
              autofocus: true,
              onKey: (RawKeyEvent event){
                if(event.runtimeType.toString() == 'RawKeyDownEvent'){
                  RawKeyEventDataAndroid data = event.data as RawKeyEventDataAndroid;
                  String _keyCode;
                  _keyCode = data.keyCode.toString(); //keycode of key event (66 is return)

                  if(_keyCode == '280' || _keyCode == '293' || _keyCode == '139') {
                    startInventoryTag();
                  }
                }
              },
              child: Column(
                children: <Widget>[
                  ConstrainedBox(
                    constraints: BoxConstraints(
                      maxHeight: 0,
                    ),
                    child: new TextField(
                      showCursor: false,
                      autofocus: true,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none
                        ),
                      ),
                    ),
                  ),
                  Offstage(
                    offstage: rfidList.length > 0 ? true : false,
                    child: Container(
                      child: Column(
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.only(top: 50),
                            child: Image.asset('assets/task.png', width: 319.w,),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 20),
                            child: Text('请手持扫描枪，对准盘点区域进行扫描', 
                            style: TextStyle(color: Utils.hexToColor('#888888'))),
                          )
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    child: Offstage(
                      offstage: rfidList.length > 0 ? false : true,
                      child: Column(
                        children: <Widget>[
                          Expanded(
                            child: SingleChildScrollView(
                              child: Column(
                                children: <Widget>[
                                  Table(
                                    columnWidths: const {
                                      //列宽
                                      0: FixedColumnWidth(50.0),
                                    },
                                    //表格边框样式
                                    border: TableBorder.all(
                                      color: Utils.hexToColor('#DCDFE6'),
                                      width: 1,
                                      style: BorderStyle.solid,
                                    ),
                                    defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                                    children: _buildTableRow()
                                  ),
                                ],
                              )
                            )
                          ),
                          Container(
                            width: double.infinity,
                            height: 35,
                            decoration: BoxDecoration(
                              border: Border(top: BorderSide(color: Utils.hexToColor('#DCDFE6'), width: 1))
                            ),
                            child: Center(
                              child: Text('每次扫描只能查看单个RFID标签的物资信息。', style: TextStyle(
                                color: Utils.hexToColor('#787878')
                              ))
                            )
                          )
                        ]
                      )
                    )
                  )
                ],
              )
            )
          ]
        )
      )
    );
  }
}